export default class SocketService {
    static instance = null;
    static get Instance () {
        if (!this.instance) {
            this.instance = new SocketService();
        }
        return this.instance;
    }

    // 和服务端连接的socket对象
    ws = null;

    // 存储回调函数
    callBackMaping = {};

    connected = false;
    sendRetyCount = 0;
    connectRetyCount = 0;

    // 定义连接服务器的方法
    connect () {
        if (!window.WebSocket) {
            return console.log('您的浏览器不支持websocket')
        }
        this.ws = new WebSocket('ws://localhost:3001');

        this.ws.onopen = () => {
            console.log('连接服务器成功');
            this.connected = true;
            this.connectRetyCount = 0;
        }
        this.ws.onclose = () => {
            console.log('连接服务器失败');
            this.connected = false;
            this.connectRetyCount++;
            setTimeout(() => {
                this.connect();
            }, 500 * this.connectRetyCount)
        }
        this.ws.onmessage = msg => {
            console.log('从服务器端获得了数据');
            const recvData = JSON.parse(msg.data)
            const socketType = recvData.socketType;
            // 判断回调函数是否存在
            if (this.callBackMaping[socketType]) {
                const action = recvData.action;
                if (action === 'getData') {
                    const realData = JSON.parse(recvData.data);
                    this.callBackMaping[socketType].call(this, realData);
                } else if (action === 'fullScreen') {

                } else if (action === 'themeChange') {

                }
            }
        }
    }

    // 回调函数注册
    registerCallBack (socketType, callBack) {
        this.callBackMaping[socketType] = callBack;
    }

    // 取消某一回调函数
    unRegisterCallBack (socketType) {
        this.callBackMaping[socketType] = null;
    }

    // 发送数据的方法
    send (data) {
        if (this.connected) {
            this.sendRetyCount = 0;
            this.ws.send(JSON.stringify(data));
        } else {
            this.sendRetyCount++;
            setTimeout(() => {
                this.send(data);
            }, this.sendRetyCount * 500)
        }
        
    }
}

